package tag.in.data;

import android.util.Log;

import tag.in.Constants;
import tag.in.utils.HTTPRequests;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Use Google Base with specified criteria to obtain Review data.
 * 
 * @author charliecollins
 */
public class TagFetcher {

    private static final String CLASSTAG = TagFetcher.class.getSimpleName();
    private static final String QAction = "action=";
    private static final String QType = "&type=";
    private static final String QOwner = "&owner=";
    private static final String QCategory = "&category=";
    private static final String QName = "&name=";
    private static final String QN = "&n=";
    private static final String QOffset = "&offset=";
    private static final String QLat = "&lat=";
    private static final String QLon = "&lon=";
    private static final String QRadious = "&radious=";
    
    private final int numResults;
    private String query;
    private final int start;

    /**
     * Construct TagFetcher with params.
     * 
     * @param location
     * @param description
     * @param rating
     * @param start
     * @param numResults
     */
    public TagFetcher(String SERVERURL, String action, String type, String owner, int category, String name, int n, int offset, double lat, double lon, int radious) {

        Log.v(Constants.LOGTAG, " " + TagFetcher.CLASSTAG + " action= " + action + " type = " + type + " owner = "
            + owner + " category = " + category + " name = " + name + " n = " + n + " offset = " + offset + " lat = " + lat + " lon = " + lon + " radious = " + radious);

        this.start = offset;
        this.numResults = n;

        // urlencode params
        try {
            if (name != null) {
                name = URLEncoder.encode(name, "UTF-8");
            }
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        
        // build query
        this.query = SERVERURL+TagFetcher.QAction+action+TagFetcher.QType+type;
        
        if ((owner != null)) {
            this.query += (TagFetcher.QOwner + owner);
        }
        if ((category != 0)) {
            this.query += (TagFetcher.QCategory + category);
        }
        if ((name != null)) {
            this.query += (TagFetcher.QName+ name);
        }
        if ((lat != 0.0)) {
            this.query += (TagFetcher.QLat + lat);
        }
        if ((lon != 0.0)) {
            this.query += (TagFetcher.QLon + lon);
        }
        if ((radious != 0)) {
            this.query += (TagFetcher.QRadious + radious);
        }
        this.query += (TagFetcher.QOffset + this.start + TagFetcher.QN + this.numResults);
        
        Log.v(Constants.LOGTAG, " " + TagFetcher.CLASSTAG + " query - " + this.query);
    }

    /**
     * Call TagInServer and parse JSON.
     * 
     * @return
     */
    public ArrayList<Tag> getTags() {
        long startTime = System.currentTimeMillis();
        ArrayList<Tag> results = new ArrayList<Tag>();
        
        HTTPRequests request = new HTTPRequests();
        String info = request.HTTPGet(this.query);
        
        JSONArray datalist = null;
        try {
			datalist = new JSONArray(info);
		} catch (JSONException e) {
			return null;
		}
		
		int i=0;
		for(i=0;i<datalist.length();i++) {
			JSONObject tuple = null;
			
			Tag data = new Tag();
			
			try {
				tuple = (JSONObject) datalist.get(i);
			} catch (JSONException e) {
			}
			
			/*
			 * If the value isnt defined it throws an exception
			 * (for each and every value ...)
			 * 
			 */
			try {
				data.id = tuple.getInt("id");
			} catch (JSONException e) {
			}
			try {
				data.name = tuple.getString("name");
			} catch (JSONException e) {
			}
			try {
				data.owner = tuple.getString("owner");
			} catch (JSONException e) {
			}
			try {
				data.category = tuple.getInt("category")-1;
			} catch (JSONException e) {
			}
			try{
				data.info = tuple.getString("info");
			} catch (JSONException e) {
			}
			try {
		        data.lat = tuple.getDouble("lat");
			} catch (JSONException e) {
			}
			try {
				data.lon = tuple.getDouble("lon");
			} catch (JSONException e) {
			}
			try {
				data.state = tuple.getString("state");
			} catch (JSONException e) {
			}
			try {
				data.imgurl = tuple.getString("imgurl");
			} catch (JSONException e) {
			}
			
			results.add(data);
		}
        
        long duration = System.currentTimeMillis() - startTime;
        Log.v(Constants.LOGTAG, " " + TagFetcher.CLASSTAG + " call and parse duration - " + duration);
        return results;
    }
}
